#include "cameraIDI.h"


float anglecam;
double _anterior, _posterior;
Point VRP;
double dist;
float angleX, angleY, angleZ;
float zoom;

void cameraIDI::computeDefaultCamera(double radi, Point centreEscena)
{
  VRP = centreEscena;
  dist = radi*2;
  _anterior = 1.;
  _posterior = 150.;
  this->radi = radi;

  hFoV = asin(radi/dist);
  hFoV = hFoV*180/PI;

  anglecam = hFoV*2*zoom;

  // inicialitzem els angles per a veure-ho des d'un cert punt de vista   
  angleX = 45;
  angleY = 45;
  angleZ = 0;
  zoom=1;
  pan_ = Point(0,0,0);
}

void cameraIDI::setModelview() 
{
  glMatrixMode(GL_MODELVIEW); //Modifiquem matriu ModelView (Camera)      
  glLoadIdentity(); //Coloquem camera a l'origent (punt per defecte)      
  trasllada(-pan_.x, -pan_.y, -dist);
  rota(angleX,1,0,0);
  rota(-angleY,0,1,0);
  trasllada(-VRP.x,-VRP.y,-VRP.z);

}

void cameraIDI::setProjection(int width, int height) 
{
  aspect=float(width)/float(height); //relació d'aspecte = amplada / alçada
  hFoV = asin(radi/dist);
  if (aspect < 1){
      hFoV = atan(tan(hFoV) / aspect);
  }
  hFoV = hFoV*180/PI; //passar a graus
  anglecam = hFoV*2*zoom;
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(anglecam, aspect, _anterior, _posterior);
}

void cameraIDI::resetCam() 
{
  angleX = 45;
  angleY = 45;
  angleZ = 0;
  radi = radi;
  zoom = 1;

  hFoV = asin(radi/dist);
  if (aspect < 1){
      hFoV = atan(tan(hFoV) / aspect);
  }
  hFoV = hFoV*180/PI;
  anglecam = hFoV*2*zoom;
  pan_ = Point(0,0,0);
}

void cameraIDI::iniciTGModelat()
{
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
}

void cameraIDI::identitat()
{
  glLoadIdentity();
}

void cameraIDI::fiTGModelat()
{
  glPopMatrix();
}

void cameraIDI::trasllada(float tx, float ty, float tz)
{
  glTranslatef(tx, ty, tz);
}

void cameraIDI::escala(float sx, float sy, float sz)
{
  glScalef(sx, sy, sz);
}

void cameraIDI::rota(float graus, float rx, float ry, float rz)
{
  glRotatef(graus, rx, ry, rz);
}

void cameraIDI::incrementaAngles(float incrX, float incrY){
    angleX +=incrY;
    angleY +=incrX;
}

void cameraIDI::incrementaZoom(float incr){
    zoom += incr;
    if(zoom < 0.1) zoom = 0.1;
    else if (zoom > 1.5) zoom = 1.5;
}

void cameraIDI::incrementaPan(float incrX, float incrY){

    pan_.x += incrX;
    pan_.y += incrY;
}
